#define NDEBUG
#include <cctype>
#include <iostream>
#include <algorithm>
#include <type_traits>

#define NV(v)#v<<" : "<<(v)
#ifdef NDEBUG
    #define DEBUG(code)
#else
    #define DEBUG(code){code}
#endif
using ull = unsigned long long;

static const size_t max_n {(size_t)2e3+5}; 
// static const size_t max_n {(size_t)10}; 
static ull k, c[max_n][max_n], prefix[max_n][max_n], t, n, m;

static void init(){
    c[0][0] = c[1][0] = c[1][1] = 1;
    for(ull i {2};i<max_n;i++){
        c[i][0]=1; 
        for(ull j{1};j<=i;j++){
            c[i][j] = (c[i-1][j-1] + c[i-1][j])%k;
        }
    }
    DEBUG(
        for(ull i{0};i<max_n;i++){
            for(ull j{0};j<=i;j++){
                std::cout<<c[i][j]<<' ';
            }
            std::cout<<'\n';
        }
        std::cout<<"===========\n";
    )
    
    for(ull i = 2;i<max_n-1;i++){ //注意这里是max_n-1
        for(ull j{1};j<=i;j++){
            prefix[i][j] = prefix[i-1][j]+prefix[i][j-1]-prefix[i-1][j-1] + (c[i][j]==0?1:0);
        } 
        prefix[i][i+1] = prefix[i][i];
    }
    DEBUG(
        for(ull i{0};i<max_n;i++){
            for(ull j{0};j<=i;j++){
                std::cout<<prefix[i][j]<<' ';
            }
            std::cout<<'\n';
        }
    )
}

template<class T>
struct ReadNumber{
    ReadNumber& operator>>(T &num){
        c=0,w=1,n=0;
        while(!isdigit(c)){
            if constexpr (!std::is_unsigned_v<T>){
                if(c=='-')w=-1;
            }
            c=getchar();
        }
        while(isdigit(c)){
            n=n*10+(c-'0');
            c=getchar();
        }
        num = w*n;
        return *this;
    }
private:
    char c;
    T w,n;
};

ReadNumber<ull> readull;

int main(){
    readull>>t>>k;
    // std::cout<<NV(t)<<'\n'<<NV(k)<<'\n';
    init();
    for(ull i {0};i<t;i++){
        // std::cout<<NV(t)<<'\n'<<NV(k)<<'\n';
        readull>>n>>m;
        // std::cout<<"test\n";
        m = std::min(m,n);
        std::cout<<(prefix[n][m])<<'\n';
    }
}